package 队列与栈;

import java.util.Stack;

//简化路径

//https://leetcode.cn/problems/simplify-path/
class 简化路径 {
    public String simplifyPath(String path) {
        String[] parts = path.split("/");
        Stack<String> stk = new Stack<>();
        // 借助栈计算最终的文件夹路径
        for (String part : parts) {
            if (part.isEmpty() || part.equals(".")) {
                continue;
            }
            if (part.equals("..")) {
                if (!stk.isEmpty()) stk.pop();
                continue;
            }
            stk.push(part);
        }
        // 栈中存储的文件夹组成路径
        StringBuilder res = new StringBuilder();
        while (!stk.isEmpty()) {
            res.insert(0, "/" + stk.pop());
        }
        return (res.isEmpty()) ? "/" : res.toString();
    }

    public static void main(String[] args) {
        System.out.println(new 简化路径().simplifyPath("/home/user/Documents/../Pictures"));
    }
}
